<?php

use app\common\controller\RedisAdmin;
use app\common\model\Category;
use fast\Form;
use fast\Tree;
use think\Db;
use think\cache\driver\Redis;

if (!function_exists('build_select')) {

    /**
     * 生成下拉列表
     * @param string $name
     * @param mixed $options
     * @param mixed $selected
     * @param mixed $attr
     * @return string
     */
    function build_select($name, $options, $selected = [], $attr = [])
    {
        $options = is_array($options) ? $options : explode(',', $options);
        $selected = is_array($selected) ? $selected : explode(',', $selected);
        return Form::select($name, $options, $selected, $attr);
    }
}

if (!function_exists('build_radios')) {

    /**
     * 生成单选按钮组
     * @param string $name
     * @param array $list
     * @param mixed $selected
     * @return string
     */
    function build_radios($name, $list = [], $selected = null)
    {
        $html = [];
        $selected = is_null($selected) ? key($list) : $selected;
        $selected = is_array($selected) ? $selected : explode(',', $selected);
        foreach ($list as $k => $v) {
            $html[] = sprintf(Form::label("{$name}-{$k}", "%s {$v}"), Form::radio($name, $k, in_array($k, $selected), ['id' => "{$name}-{$k}"]));
        }
        return '<div class="radio">' . implode(' ', $html) . '</div>';
    }
}

if (!function_exists('build_checkboxs')) {

    /**
     * 生成复选按钮组
     * @param string $name
     * @param array $list
     * @param mixed $selected
     * @return string
     */
    function build_checkboxs($name, $list = [], $selected = null)
    {
        $html = [];
        $selected = is_null($selected) ? [] : $selected;
        $selected = is_array($selected) ? $selected : explode(',', $selected);
        foreach ($list as $k => $v) {
            $html[] = sprintf(Form::label("{$name}-{$k}", "%s {$v}"), Form::checkbox($name, $k, in_array($k, $selected), ['id' => "{$name}-{$k}"]));
        }
        return '<div class="checkbox">' . implode(' ', $html) . '</div>';
    }
}


if (!function_exists('build_category_select')) {

    /**
     * 生成分类下拉列表框
     * @param string $name
     * @param string $type
     * @param mixed $selected
     * @param array $attr
     * @param array $header
     * @return string
     */
    function build_category_select($name, $type, $selected = null, $attr = [], $header = [])
    {
        $tree = Tree::instance();
        $tree->init(Category::getCategoryArray($type), 'pid');
        $categorylist = $tree->getTreeList($tree->getTreeArray(0), 'name');
        $categorydata = $header ? $header : [];
        foreach ($categorylist as $k => $v) {
            $categorydata[$v['id']] = $v['name'];
        }
        $attr = array_merge(['id' => "c-{$name}", 'class' => 'form-control selectpicker'], $attr);
        return build_select($name, $categorydata, $selected, $attr);
    }
}

if (!function_exists('build_toolbar')) {

    /**
     * 生成表格操作按钮栏
     * @param array $btns 按钮组
     * @param array $attr 按钮属性值
     * @return string
     */
    function build_toolbar($btns = null, $attr = [])
    {
        $auth = \app\admin\library\Auth::instance();
        $controller = str_replace('.', '/', strtolower(think\Request::instance()->controller()));
        $btns = $btns ? $btns : ['refresh', 'add', 'edit', 'del', 'import'];
        $btns = is_array($btns) ? $btns : explode(',', $btns);
        $index = array_search('delete', $btns);
        if ($index !== false) {
            $btns[$index] = 'del';
        }
        $btnAttr = [
            'refresh' => ['javascript:;', 'btn btn-primary btn-refresh', 'fa fa-refresh', '', __('Refresh')],
            'add' => ['javascript:;', 'btn btn-success btn-add', 'fa fa-plus', __('Add'), __('Add')],
            'edit' => ['javascript:;', 'btn btn-success btn-edit btn-disabled disabled', 'fa fa-pencil', __('Edit'), __('Edit')],
            'del' => ['javascript:;', 'btn btn-danger btn-del btn-disabled disabled', 'fa fa-trash', __('Delete'), __('Delete')],
            'import' => ['javascript:;', 'btn btn-info btn-import', 'fa fa-upload', __('Import'), __('Import')],
        ];
        $btnAttr = array_merge($btnAttr, $attr);
        $html = [];
        foreach ($btns as $k => $v) {
            //如果未定义或没有权限
            if (!isset($btnAttr[$v]) || ($v !== 'refresh' && !$auth->check("{$controller}/{$v}"))) {
                continue;
            }
            list($href, $class, $icon, $text, $title) = $btnAttr[$v];
            //$extend = $v == 'import' ? 'id="btn-import-file" data-url="ajax/upload" data-mimetype="csv,xls,xlsx" data-multiple="false"' : '';
            //$html[] = '<a href="' . $href . '" class="' . $class . '" title="' . $title . '" ' . $extend . '><i class="' . $icon . '"></i> ' . $text . '</a>';
            if ($v == 'import') {
                $template = str_replace('/', '_', $controller);
                $download = '';
                if (file_exists("./template/{$template}.xlsx")) {
                    $download .= "<li><a href=\"/template/{$template}.xlsx\" target=\"_blank\">XLSX模版</a></li>";
                }
                if (file_exists("./template/{$template}.xls")) {
                    $download .= "<li><a href=\"/template/{$template}.xls\" target=\"_blank\">XLS模版</a></li>";
                }
                if (file_exists("./template/{$template}.csv")) {
                    $download .= empty($download) ? '' : "<li class=\"divider\"></li>";
                    $download .= "<li><a href=\"/template/{$template}.csv\" target=\"_blank\">CSV模版</a></li>";
                }
                $download .= empty($download) ? '' : "\n                            ";
                if (!empty($download)) {
                    $html[] = <<<EOT
                        <div class="btn-group">
                            <button type="button" href="{$href}" class="btn btn-info btn-import" title="{$title}" id="btn-import-file" data-url="ajax/upload" data-mimetype="csv,xls,xlsx" data-multiple="false"><i class="{$icon}"></i> {$text}</button>
                            <button type="button" class="btn btn-info dropdown-toggle" data-toggle="dropdown" title="下载批量导入模版">
                                <span class="caret"></span>
                                <span class="sr-only">Toggle Dropdown</span>
                            </button>
                            <ul class="dropdown-menu" role="menu">{$download}</ul>
                        </div>
EOT;
                } else {
                    $html[] = '<a href="' . $href . '" class="' . $class . '" title="' . $title . '" id="btn-import-file" data-url="ajax/upload" data-mimetype="csv,xls,xlsx" data-multiple="false"><i class="' . $icon . '"></i> ' . $text . '</a>';
                }
            } else {
                $html[] = '<a href="' . $href . '" class="' . $class . '" title="' . $title . '"><i class="' . $icon . '"></i> ' . $text . '</a>';
            }
        }
        return implode(' ', $html);
    }
}

if (!function_exists('build_heading')) {

    /**
     * 生成页面Heading
     *
     * @param string $path 指定的path
     * @return string
     */
    function build_heading($path = null, $container = true)
    {
        $title = $content = '';
        if (is_null($path)) {
            $action = request()->action();
            $controller = str_replace('.', '/', request()->controller());
            $path = strtolower($controller . ($action && $action != 'index' ? '/' . $action : ''));
        }
        // 根据当前的URI自动匹配父节点的标题和备注
        $data = Db::name('ca_auth_rule')->where('name', $path)->field('title,remark')->find();
        if ($data) {
            $title = __($data['title']);
            $content = __($data['remark']);
        }
        if (!$content) {
            return '';
        }
        $result = '<div class="panel-lead"><em>' . $title . '</em>' . $content . '</div>';
        if ($container) {
            $result = '<div class="panel-heading">' . $result . '</div>';
        }
        return $result;
    }
}

if (!function_exists('build_suffix_image')) {
    /**
     * 生成文件后缀图片
     * @param string $suffix 后缀
     * @param null $background
     * @return string
     */
    function build_suffix_image($suffix, $background = null)
    {
        $suffix = mb_substr(strtoupper($suffix), 0, 4);
        $total = unpack('L', hash('adler32', $suffix, true))[1];
        $hue = $total % 360;
        list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);

        $background = $background ? $background : "rgb({$r},{$g},{$b})";

        $icon = <<<EOT
        <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 512 512" style="enable-background:new 0 0 512 512;" xml:space="preserve">
            <path style="fill:#E2E5E7;" d="M128,0c-17.6,0-32,14.4-32,32v448c0,17.6,14.4,32,32,32h320c17.6,0,32-14.4,32-32V128L352,0H128z"/>
            <path style="fill:#B0B7BD;" d="M384,128h96L352,0v96C352,113.6,366.4,128,384,128z"/>
            <polygon style="fill:#CAD1D8;" points="480,224 384,128 480,128 "/>
            <path style="fill:{$background};" d="M416,416c0,8.8-7.2,16-16,16H48c-8.8,0-16-7.2-16-16V256c0-8.8,7.2-16,16-16h352c8.8,0,16,7.2,16,16 V416z"/>
            <path style="fill:#CAD1D8;" d="M400,432H96v16h304c8.8,0,16-7.2,16-16v-16C416,424.8,408.8,432,400,432z"/>
            <g><text><tspan x="220" y="380" font-size="124" font-family="Verdana, Helvetica, Arial, sans-serif" fill="white" text-anchor="middle">{$suffix}</tspan></text></g>
        </svg>
EOT;
        return $icon;
    }
}
function get_pro($flag = '')
{  //省份
    $where = "id<96";
    if (empty($flag)) $where .= " AND id>1";
//    dump($where);exit;
    // $province=DB::name('province')->where($where)->order('sort1,py')->cache(300)->select();
    $province = DB::name('province')->where($where)->order('sort desc')->cache(300)->select();
    return $province;
}

function get_parent_anth()
{
    $p_rules = Db::name('ca_auth_rule')
        ->field("id")
        ->where('id>1 and pid=0 AND ismenu=1 AND status="normal"')
        ->select();
    return array_column($p_rules, 'id');

}

function get_pid($pid)
{
    $res = Db::name('ca_auth_rule')
        ->field('id,pid')
        ->where("id=" . $pid . "")
        ->find();
    return $res;
}

function get_pro_auth($url, $mid = '')
{  //省份 1查大学 2查升学 3查专业 4查数据 5查试卷
    if ($mid == 1) {
        //   $province=DB::name('province')->where('id<96')->order('sort1,py')->select();
        $province = DB::name('province')->where('id<96')->order('sort desc')->select();
    } else {
        $p_list = get_parent_anth();
        $type = 0;
        $data = Db::name('ca_auth_rule')
            ->field('id,pid')
            ->where("name='" . $url . "'")
            ->find();
        if (in_array($data['id'], $p_list)) {
            $type = $data['id'];
        } else {
            $id = get_pid($data['pid']);
            if (in_array($id['id'], $p_list)) {
                $type = $id['id'];
            } else {
                $id2 = get_pid($id['pid']);
                if (in_array($id2['id'], $p_list)) {
                    $type = $id2['id'];
                }
            }
        }
        if (!$mid) $mid = session('admin.id');
        $res = DB::name('ca_auth_province')->where(['type' => $type, 'm_id' => $mid])->find();
        if (empty($res['province'])) return [];
//    $res["province"]='2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33';

        if ($type == 521 || $type == 614) {
            $res['province'] = $res['province'] . ',1';
        }

        // $province=DB::name('province')->where('id<96  and id IN ('.$res["province"].')')->order('sort1,py')->select();
        $province = DB::name('province')->where('id<96  and id IN (' . $res["province"] . ')')->order('sort desc')->select();
    }

    return $province;
}

function get_paper_type()
{  //试卷类型
    $res = DB::name('zd_paper_type')->where('is_del=0')->order('id asc')->select();
    return $res;
}


function check_mobile($phone)
{
    if (preg_match("/^1[123456789]{1}\d{9}$/", $phone)) {
        return true;
    } else {
        return false;
    }
}

function json_fail($msg = '请求失败')
{
    return ['status' => 400, 'msg' => $msg];
}

function get_sms_code()
{
    return rand(100000, 999999);
}

function curl_https($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_HEADER, FALSE);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_REFERER, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $result = curl_exec($ch);
    curl_close($ch);
    //-------请求为空
    if (empty($result)) {
        return false;
    }
    return $result;
}

function curl2($url, $data)
{
    //dump(json_encode($data, JSON_UNESCAPED_UNICODE));
    if ($url && count($data)) {
        $headers = ['Content-Type' => 'application/json'];
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data, JSON_UNESCAPED_UNICODE));
        $res = curl_exec($ch);
        curl_close($ch);
        return $res;
    }
}

function curl($url, $val = '')
{
    $ch = curl_init();  //初始化curl
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);  //使用post请求
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    //curl_setopt ( $ch, CURLOPT_POSTFIELDS, $val);  //提交数据
    if ($val) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($val));
    } else {
        curl_setopt($ch, CURLOPT_POSTFIELDS, $val);
    }
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);  //重定向地址也输出
    $return = curl_exec($ch); //得到返回值
    curl_close($ch);  //关闭
    return $return;
}

if (!function_exists('get_province_name')) {

    /**
     * $province_id
     * @return string
     */
    function get_province_name($province_id)
    {
        $province_name = RedisAdmin::getInstance(1)->get('get_province_name_' . $province_id);
        if (!$province_name) {
            $province_name = Db::name('province')->where(['id' => $province_id])->value('name');
            RedisAdmin::getInstance(1)->set('get_province_name_' . $province_id, $province_name);
        }
        return $province_name;
    }
}
if (!function_exists('get_city_name')) {

    /**
     * $city_id
     * @return string
     */
    function get_city_name($city_id)
    {
        $city_name = RedisAdmin::getInstance(1)->get('get_city_name_' . $city_id);
        if (!$city_name) {
            $city_name = Db::name('province_city')->where(['id' => $city_id])->value('city');
            RedisAdmin::getInstance(1)->set('get_city_name_' . $city_id, $city_name);
        }
        return $city_name;
    }
}
if (!function_exists('get_region_name')) {

    /**
     * $region_id
     * @return string
     */
    function get_region_name($region_id)
    {
        $region_name = RedisAdmin::getInstance(1)->get('get_region_name_' . $region_id);
        if (!$region_name) {
            $region_name = Db::name('province_city_region')->where(['id' => $region_id])->value('region');
            RedisAdmin::getInstance(1)->set('get_region_name_' . $region_id, $region_name);
        }
        return $region_name;
    }
}
if (!function_exists('get_school_name')) {

    /**
     * $school_id
     * @return string
     */
    function get_school_name($school_id)
    {
        $school_name = RedisAdmin::getInstance(1)->get('get_school_name_' . $school_id);
        if (!$school_name) {
            $school_name = Db::name('school_z')->where(['id' => $school_id])->value('school');
            RedisAdmin::getInstance(1)->set('get_school_name_' . $school_id, $school_name);
        }
        return $school_name;
    }
}
if (!function_exists('get_middle_school_name')) {

    /**
     * $school_id
     * @return string
     */
    function get_middle_school_name($school_id)
    {
        $school_name = RedisAdmin::getInstance(1)->get('get_middle_school_name_' . $school_id);
        if (!$school_name) {
            $school_name = Db::name('zd_middle_school')->where(['id' => $school_id])->value('school');
            RedisAdmin::getInstance(1)->set('get_middle_school_name' . $school_id, $school_name);
        }
        return $school_name;
    }
}

if (!function_exists('hide_mobile')) {

    /**
     * $phone
     */
    function hide_mobile($phone)
    {
        $IsWhat = preg_match('/(0[0-9]{2,3}[\-]?[2-9][0-9]{6,7}[\-]?[0-9]?)/i', $phone); //固定电话
        if ($IsWhat == 1) {
            return preg_replace('/(0[0-9]{2,3}[\-]?[2-9])[0-9]{3,4}([0-9]{3}[\-]?[0-9]?)/i', '$1****$2', $phone);
        } else {
            return preg_replace('/(1[358]{1}[0-9])[0-9]{4}([0-9]{4})/i', '$1****$2', $phone);
        }
    }
}


if (!function_exists('send_sms')) {
    /**
     */
    function send_sms($phone, $content)
    {
        $apiAccount = 'S14652';
        $secretKey = 'fd5dd8e8-207c-4da8-b726-a7fa5ff82c7a';
        $url = 'http://112.48.132.180:8001/';

        $url = $url . 'sendsms?apiAccount=' . $apiAccount . '&secretKey=' . $secretKey . '&mobiles=' . $phone . '&content=' . urlencode($content);
        return json_decode(curl($url, ''), true);
    }
}

if (!function_exists('get_group_admin')) {

    /**
     * $group_id
     */
    function get_group_admin($group_id, $type = 1)
    {
        $group_info = Db::name('ca_auth_group')->where(['id' => $group_id])->field('id,pid')->find();
        //     var_dump($group_info);
        if ($group_info['pid'] > 0 && $group_info['pid'] > 2) {
            if ($type == 2) {
                $group_info = Db::name('ca_auth_group')->where(['id' => $group_info['pid']])->field('id,pid')->find();
            } else {
                return get_group_admin($group_info['pid']);
            }
            //  return  get_group_admin($group_info['pid']);
            //
        }
        //  var_dump($group_info['id']);
        $uid = Db::name('ca_auth_group_access')->where(['group_id' => $group_info['id']])->column('uid');
        $nickname = Db::name('ca_admin')->where(['id' => ['in', $uid], 'status' => 'normal'])->value('nickname');
        return $nickname;
    }
}
if (!function_exists('get_top_group_id')) {

    /**
     * $group_id
     */
    function get_top_group_id($group_id, $type = 1)
    {
        $group_info = Db::name('ca_auth_group')->where(['id' => $group_id])->field('id,pid')->find();
        //     var_dump($group_info);
        if ($group_info['pid'] > 0 && $group_info['pid'] > 2) {
            if ($type == 2) {
                $group_info = Db::name('ca_auth_group')->where(['id' => $group_info['pid']])->field('id,pid')->find();
            } else {
                return get_top_group_id($group_info['pid']);
            }
            //  return  get_group_admin($group_info['pid']);
            //
        }
        //  var_dump($group_info['id']);
//        $uid = Db::name('ca_auth_group_access')->where(['group_id'=>$group_info['id']])->column('uid');
//        $nickname = Db::name('admin')->where(['id'=>['in',$uid],'status'=>'normal'])->value('nickname');
        return $group_info['id'];

    }
}

if (!function_exists('get_rand_str')) {

    /**
     * $group_id
     */
    function get_rand_str($length)
    {
        $str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
        $randStr = str_shuffle($str);
        $rands = substr($randStr, 0, $length);
        return $rands;

    }
}
if (!function_exists('get_up_str')) {

    /**
     * $group_id
     */
    function get_up_str($length)
    {
        $str = 'ABCDEFGHIJKLMNPQRSTUVWXYZ';
        $randStr = str_shuffle($str);
        $rands = substr($randStr, 0, $length);
        return $rands;

    }
}
if (!function_exists('get_rand_num')) {

    /**
     * $group_id
     */
    function get_rand_num($length)
    {
        $str = '1234567890';
        $randStr = str_shuffle($str);
        $rands = substr($randStr, 0, $length);
        return $rands;

    }
}

if (!function_exists('get_distributor_info')) {

    /**
     * $group_id
     */
    function get_distributor_info($distributor_id)
    {
        $distributor_info = Db::name('cd_admin')->where(['id' => $distributor_id])->field('*')->find();
        return $distributor_info;

    }
}
if (!function_exists('get_rand_str')) {

    /**
     * $group_id
     */
    function get_rand_str($length, $type = 1)
    {
        if ($type == 1) {
            $str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789';
        } else if ($type == 2) {
            $str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        }else if ($type == 3) {
            $str = '123456789';
        }

        $randStr = str_shuffle($str);
        $rands = substr($randStr, 0, $length);
        return $rands;

    }
}

if (!function_exists('get_city')) {

    /**
     * $province
     */
    function get_city($province)
    {
        $arr=Db::name('province_city_region')
            ->field('city')
            ->where(['province'=>$province])
            ->group('city')
            ->order('id asc')
            ->select();
        return $arr;

    }
}


